| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434 | 1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
| ;(function(factory) {
'use strict';
var w = (0, eval)('this');
var MODULE_NAME = 'FileDnD',
registered = false;
Iif (typeof define === 'function' && define.amd) {
define(factory.bind(this, w));
registered = true;
}
Iif (typeof exports === 'object') {
module.exports = factory(w);
registered = true;
}
Iif (registered) { return; }
var old = w[MODULE_NAME],
api = w[MODULE_NAME] = factory(w);
api.noConflict = function () {
w[MODULE_NAME] = old;
return api;
};
})(function(global) {
'use strict';
var window = global,
document = window.document;
function _emitter() {
var f = window.document.createDocumentFragment();
function d(m) {
this[m] = f[m].bind(f);
}
['addEventListener','dispatchEvent','removeEventListener']
.forEach(d, this);
}
/**
* Create drag & drop zone for file,
* and preview read file after file upload.
*
* @param {string|HTMLElement} el To define drag & drop file zone element or selector.
* @param {object} [configure] configure settings
* @prop {HTMLElement} [preview] To preview HTMLImageElement's into this element.
* @prop {string} [dragoverClass] Adding class to dndzone when dispached dragover event on dndzone.
* @prop {boolean} [autoPreview] will automatically preview when `el` get files. default true.
* @prop {boolean} [autoRefresh] will automatically refresh preview element when files uploaded. default true.
* @prop {string} [imageMinWidth] min-width of preview's <img>. default null.
* @prop {string} [imageMinHeight] min-height of preview's <img>. default null.
* @prop {string} [imageMaxWidth] max-width of preview's <img>. default null.
* @prop {string} [imageMaxHeight] max-height of preview's <img>. default null.
* @example
* var el = document.getElementById('drag-and-drop-zone');
* var preview = document.getElementById('preview-zone');
*
* var filednd = new FileDnD(el, {
* preview: preview,
* dragoverClass: 'emphasis',
* autoPreview: true
* autoRefresh: true
* imageMinWidth: '100px',
* imageMinHeight: '100px',
* imageMaxWidth: '100%',
* imageMaxHeight: '100%',
* });
*
* filednd.addEventListener('upload', function(e) {
* console.log(JSON.stringify(e.detail));
* });
*
* filednd.addEventListener('uploadend', function(e) {
* console.log(JSON.stringify(e.detail));
* });
*
* @constructor
*/
function FileDnD(el, configure) {
var _configure = configure || {},
_el = _utils.makeElement(el);
_emitter.call(this);
this._isFileElement = false;
if (_el instanceof HTMLInputElement) {
if (_el.type !== 'file') {
throw TypeError('"el" is HTMLElement but not input[type="file"].');
}
this._isFileElement = true;
}
this._el = _el;
this._files = [];
if (_configure.preview) {
this._preview = _utils.makeElement(_configure.preview);
}
if (_configure.dragoverClass) {
this._dragoverClass = _configure.dragoverClass;
}
this._autoPreview = typeof _configure.autoPreview === 'undefined' ?
true : _configure.autoPreview;
this._autoRefresh = typeof _configure.autoRefresh === 'undefined' ?
true : _configure.autoRefresh;
this._imageMinWidth = _configure.imageMinWidth || null;
this._imageMinHeight = _configure.imageMinHeight || null;
this._imageMaxWidth = _configure.imageMaxWidth || null;
this._imageMaxHeight = _configure.imageMaxHeight || null;
this._attachEvent();
};
/**
* Attach event to "el" (HTMLElement)
*/
FileDnD.prototype._attachEvent = function() {
var _this = this,
el = _this._el;
if (this._isFileElement) {
el.addEventListener('change', this.onChangeDefault.bind(this));
} else {
el.addEventListener('dragover', this.onDragoverDefault.bind(this));
el.addEventListener('dragleave', this.onDragleaveDefault.bind(this));
el.addEventListener('drop', this.onDropDefault.bind(this));
}
};
/**
* when this instance's `el` is input[type="files"] or that selecter,
* this function called as `el`'s onchange event listener.
*
* @param {Event} e input[type=\"file\"] `onchange` event.
*/
FileDnD.prototype.onChangeDefault = function(e) {
var _this = this,
el = _this._el;
_this.dispatchEvent(new CustomEvent('upload', {
detail: {
currentFiles: _this.getFiles(),
targetFiles: e.target.files
}
}));
if (_this._dragoverClass) {
_utils.removeClass(el, _this._dragoverClass);
}
if (_this._autoRefresh) {
_this.clearFiles();
_this.applyToHTML();
}
_this.addFiles(e.target.files);
if (_this._autoPreview) {
_this.applyToHTML();
}
_this.dispatchEvent(new CustomEvent('uploadend', {
detail: {
currentFiles: _this.getFiles(),
targetFiles: e.target.files
}
}));
};
/**
* when this instance's `el` is normal HTMLElement or that selecter,
* this function called as `el`'s ondragover event listener.
*
* @param {Event} e this.el's `ondragover` event.
*/
FileDnD.prototype.onDragoverDefault = function(e) {
var _this = this,
el = _this._el;
_utils.stopEvent(e);
if (_this._dragoverClass) {
_utils.addClass(el, _this._dragoverClass);
}
};
/**
* when this instance's `el` is normal HTMLElement or that selecter,
* this function called as `el`'s ondragleave event listener.
*
* @param {Event} e this.el's `ondragleave` event.
*/
FileDnD.prototype.onDragleaveDefault = function(e) {
var _this = this,
el = _this._el;
_utils.stopEvent(e);
if (_this._dragoverClass) {
_utils.removeClass(el, _this._dragoverClass);
}
};
/**
* when this instance's `el` is normal HTMLElement or that selecter,
* this function called as `el`'s ondragleave event listener.
*
* @param {Event} e this.el's `ondrop` event.
*/
FileDnD.prototype.onDropDefault = function(e) {
var _this = this,
el = _this._el;
_utils.stopEvent(e);
_this.dispatchEvent(new CustomEvent('upload', {
detail: {
currentFiles: _this.getFiles(),
targetFiles: e.dataTransfer.files
}
}));
if (_this._dragoverClass) {
_utils.removeClass(el, _this._dragoverClass);
}
if (_this._autoRefresh) {
_this.clearFiles();
_this.applyToHTML();
}
_this.addFiles(e.dataTransfer.files);
if (_this._autoPreview) {
_this.applyToHTML();
}
_this.dispatchEvent(new CustomEvent('uploadend', {
detail: {
currentFiles: _this.getFiles(),
targetFiles: e.dataTransfer.files
}
}));
};
/**
* Get HTMLElement: `el` drag and drop zone's element.
*/
FileDnD.prototype.getEl = function() {
return this._el;
};
/**
* Get HTMLElement: file preview zone's element.
*/
FileDnD.prototype.getPreviewZone = function() {
return this._preview;
};
/**
* Get uploaded file list.
*/
FileDnD.prototype.getFiles = function() {
return this._files;
};
/**
* Add file list.
* @param {Array} files Files from drag and drop or input[type=file] changed.
*/
FileDnD.prototype.addFiles = function(files) {
var _this = this;
if (files instanceof Array || files instanceof FileList) {
[].filter.call(files, function(f) {
return f instanceof File || f instanceof Blob;
}).forEach(function(f) {
_this.addFile(f);
});
}
if (files instanceof File || files instanceof Blob) {
_this.addFile(files);
}
};
/**
* Add a file.
* @param {File|Blob} file push to FileDnD#_files
*/
FileDnD.prototype.addFile = function(file) {
if (file instanceof File || file instanceof Blob) {
this._files.push(file);
}
};
/**
* Clear uploaded file list and preview zone.
*/
FileDnD.prototype.clearFiles = function() {
this._files = [];
};
/**
* Has files apply to html source
*/
FileDnD.prototype.applyToHTML = function() {
if (this._preview) {
this.removeFromPreviewHTML();
this.appendToPreviewHTML();
}
};
/**
* remove html from preview element.
*/
FileDnD.prototype.removeFromPreviewHTML = function() {
if (this._preview) {
this._preview.innerHTML = '';
}
};
/**
* Preview uploaded files.
*/
FileDnD.prototype.appendToPreviewHTML = function() {
var _this = this;
if (!_this._preview) {
throw Error('Not configure option: preview');
}
var fragment = document.createDocumentFragment();
Array.prototype.forEach.call(_this._files, function(f) {
var obj = _previewElementFactory(f);
obj.style['min-width'] = _this._imageMinWidth;
obj.style['min-height'] = _this._imageMinHeight;
obj.style['max-width'] = _this._imageMaxWidth;
obj.style['max-height'] = _this._imageMaxHeight;
fragment.appendChild(obj);
});
_this._preview.appendChild(fragment);
};
function _previewElementFactory(file) {
if (!(file instanceof File || file instanceof Blob)) {
throw TypeError('invalid argument type: required File or Blob, but found ' + file.type);
}
var reader = new FileReader();
if (/image\/.*/.test(file.type)) {
var img = document.createElement('img');
reader.readAsDataURL(file);
reader.onloadend = function() {
img.src = reader.result;
};
return img;
}
if (/application\/pdf/.test(file.type)) {
var obj = document.createElement('object');
obj.type = 'application/pdf';
reader.readAsDataURL(file);
reader.onloadend = function() {
obj.data = reader.result;
};
return obj;
}
if (/text\/(.+)/.test(file.type)) {
var pre = document.createElement('pre');
reader.readAsText(file);
reader.onloadend = function() {
pre.innerHTML = _utils.escapeHTML(reader.result);
};
return pre;
}
throw TypeError('Not support file type: ' + file.type);
}
var _utils = {
stopEvent: function(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
},
addClass: function(to, className) {
if (className) {
if (!to.classList.contains(className)) {
to.classList.add(className);
}
}
},
removeClass: function(to, className) {
if (className) {
if (to.classList.contains(className)) {
to.classList.remove(className);
}
}
},
makeElement: function(el) {
if (el instanceof HTMLElement) {
return el;
}
if (typeof el === 'string') {
var _el = document.querySelector(el);
if (!_el) {
throw Error('Not found in document.querySelector(el)');
}
return _el;
}
throw TypeError('"el" is not HTMLElement or valid selector.');
},
escapeHTML: function(str) {
return typeof str !== 'string' ? str :
str.replace(/[&'`"<>]/g, function(match) {
return {
'&': '&',
"'": ''',
'`': '`',
'"': '"',
'<': '<',
'>': '>'
}[match];
});
}
};
return FileDnD;
});
|